<?php

namespace App\Models;

use Elasticsearch\ClientBuilder;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    public $timestamps = false;

    public function toSearchableArray()
    {
        return [
            'goods_name' => $this->goods_name,
            'taobao_title' => $this->taobao_title,
            'tbid' => $this->tbid,
            'taoke_price' => $this->taoke_price,
            'quan_fee' => $this->quan_fee,
            'tmall' => $this->tmall,
            'sort' => $this->sort,
            'is_top' => $this->is_top,
            'update_time' => $this->update_time,
        ];
    }

    /**
     * 创建es索引
     * @return bool
     */
    public function createEsIndex(){
        $client = ClientBuilder::create()->setHosts(\Config::get('elasticsearch.hosts'))->build();
        $params = [
            'index' => \Config::get('elasticsearch.index'),
            'body' => [
                'settings' => [
                    'number_of_shards' => 5,
                    'number_of_replicas' => 0
                ],
                'mappings' => [
                    $this->table => [
                        '_source' => [
                            'enabled' => true,
                        ],
                        'properties' => [
                            'goods_name' => [
                                'type' => 'text',
                                'analyzer' => 'ik_max_word',
                                'search_analyzer' => 'ik_max_word',
                                'fielddata' => true
                            ],
                            'taobao_title' => [
                                'type' => 'text',
                                'analyzer' => 'ik_max_word',
                                'search_analyzer' => 'ik_max_word',
                                'fielddata' => true
                            ],
                            'tbid' => [
                                'type' => 'keyword',
                            ],
                            'taoke_price' => [
                                'type' => 'integer',
                            ],
                            'quan_fee' => [
                                'type' => 'integer',
                            ],
                            'tmall' => [
                                'type' => 'integer',
                            ],
                            'sort' => [
                                'type' => 'integer',
                            ],
                            'is_top' => [
                                'type' => 'integer',
                            ],
                            'update_time' => [
                                'type' => 'date',
                                'format' => 'yyyy-MM-dd HH:mm:ss||epoch_millis',
                            ]
                        ]
                    ]
                ]
            ]
        ];
        try {
            $response = $client->indices()->create($params);
            if(isset($response['acknowledged']) && $response['acknowledged'] == 1){
                return true;
            }else{
                return false;
            }
        }catch (\Exception $e){
            \Log::debug($e);
            return false;
        }
    }

    /**
     * update data to es
     * @param $data
     * @return bool
     */
    public function updateEsData($id, $data){
        try {
            if(is_array($data)){
                $data = (object)$data;
            }
            $params = [
                'index' => \Config::get('elasticsearch.index'),
                'type' => $this->table,
                'id' => $id,
                'body' => [
                    'goods_name' => $data->goods_name,
                    'taobao_title' => $data->taobao_title,
                    'tbid' => $data->tbid,
                    'taoke_price' => $data->taoke_price,
                    'quan_fee' => $data->quan_fee,
                    'tmall' => $data->tmall,
                    'sort' => $data->sort,
                    'is_top' => $data->is_top,
                    'update_time' => date('Y-m-d H:i:s', strtotime($data->update_time)),
                ]
            ];
            $client = ClientBuilder::create()->setHosts(\Config::get('elasticsearch.hosts'))->build();
            $response = $client->index($params);
            \Log::debug(json_encode($response));
            if(isset($response['_shards']['successful']) && $response['_shards']['successful'] == 1){
                return true;
            }else{
                return false;
            }
        }catch (\Exception $e){
            \Log::debug($e);
            return false;
        }
    }

    /**
     * delete data to es
     * @param $id
     * @return bool
     */
    public function deleteEsData($id){
        try {
            $params = [
                'index' => \Config::get('elasticsearch.index'),
                'type' => $this->table,
                'id' => $id,
            ];
            $client = ClientBuilder::create()->setHosts(\Config::get('elasticsearch.hosts'))->build();
            $response = $client->delete($params);
            \Log::debug(json_encode($response));
            if (isset($response['_shards']['successful']) && $response['_shards']['successful'] == 1) {
                return true;
            } else {
                return false;
            }
        }catch (\Exception $e){
            \Log::debug($e);
            return false;
        }
    }

    public function searchEsData($search, $offset=0, $length=20){
        $response = [
            'total' => 0,
            'goods' => []
        ];
        try {
            $params = [
                'index' => \Config::get('elasticsearch.index'),
                'type' => $this->table,
                'from' => $offset,
                'size' => $length,
                'body' => [
                    'query' => [
                        'match' => [
                            'goods_name' => $search
                        ]
                    ]
                ]
            ];
            $client = ClientBuilder::create()->setHosts(\Config::get('elasticsearch.hosts'))->build();
            $esResponse = $client->search($params);

            $response['total'] = $esResponse['hits']['total'];
            foreach ($esResponse['hits']['hits'] as $es){
                $response['goods'][] = $es['_source'];
            }
            return $response;
        }catch (\Exception $e){
            \Log::debug($e);
            return $response;
        }
    }
}
